import {
  x as C,
  r as ae,
  i as u,
  o as i,
  a as z,
  m as e,
  l,
  k as y,
  F as J,
  j as X,
  b as f,
  t as V,
  e as s,
  u as j,
  O as K,
  P as R,
  Q as ee,
  B as g,
} from "./index-abba05ce.js";

const Ye = { class: "admin-lists" },
  Ze = { class: "border-none mt-2" },
  Je = { class: "d-flex" },
  Xe = { class: "filters" },
  Ke = { class: "border-none mt-3" },
  Qe = { class: "d-flex justify-content-end mt-4" };

const STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "正常", value: 1 },
  { label: "隐藏", value: 2 },
  { label: "待审核", value: 3 },
];

const formatStatusText = (status) => {
  switch (status) {
    case 1: return "正常";
    case 2: return "隐藏";
    case 3: return "待审核";
    default: return "-";
  }
};

const formatTimestamp = (value) => {
  if (!value) return "-";
  const timestamp = String(value).length === 10 ? Number(value) * 1e3 : Number(value);
  if (!timestamp || Number.isNaN(timestamp)) return "-";
  const date = new Date(timestamp);
  if (Number.isNaN(date.getTime())) return "-";
  const pad = (num) => `${num}`.padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};

const et = {
  __name: "index",
  setup() {
    const filters = ae({ id: "", title: "", category_id: "", status: "" });
    const tableData = C([]);
    const categories = C([]);
    const loading = C(!1);
    const pagination = ae({ page: 1, pageSize: 20, total: 0 });

    const buildParams = () => {
      const params = {
        page: pagination.page,
        page_size: pagination.pageSize,
      };
      if (filters.id) params.id = filters.id;
      if (filters.title) params.title = filters.title;
      if (filters.category_id) params.category_id = filters.category_id;
      if (filters.status !== "") params.status = filters.status;
      return params;
    };

    const fetchList = async () => {
      loading.value = !0;
      try {
        const res = await K.science.list(buildParams());
        if (res.error) {
          R.msgError(res.msg || "获取列表失败");
          return;
        }
        const data = res.data || {};
        tableData.value = data.list || [];
        pagination.total = data.total || 0;
        pagination.page = data.page || pagination.page;
        pagination.pageSize = data.pageSize || pagination.pageSize;
      } catch (err) {
        console.error("fetch science list error", err);
        R.msgError("获取列表失败");
      } finally {
        loading.value = !1;
      }
    };

    // 添加处理添加按钮点击事件
    const handleAdd = () => {
         // 编辑功能，跳转到编辑页面
      window.location.href = new URL(`/science/edit/index`, window.location.origin).href;
   
    };

    // 编辑功能
    const handleEdit = (row) => {
      // 编辑功能，跳转到编辑页面
      console.log("编辑科学知识", row);
      window.location.href = new URL(`/science/edit/index?id=${row.id}`, window.location.origin).href;
    };

    // 查看详情
    const handleView = (row) => {
      // 查看详情功能，跳转到编辑页面但可能需要设置为只读模式
      console.log("查看科学知识详情", row);
      window.location.href = new URL(`/science/edit/index?id=${row.id}&view=1`, window.location.origin).href;
    };

    const handleStatusChange = async (row) => {
      try {
        // 切换状态功能
        const newStatus = row.status === 1 ? 2 : 1;
        const res = await K.science.update({
          id: row.id,
          status: newStatus
        });
        if (res.error) {
          R.msgError(res.msg || "状态更新失败");
          return;
        }
        R.msgSuccess("状态更新成功");
        fetchList(); // 重新获取列表数据
      } catch (err) {
        console.error("update status error", err);
        R.msgError("状态更新失败");
      }
    };

    const fetchCategories = async () => {
      try {
        const response = await fetch("/science/api/categories");
        const json = await response.json();
        if ((json.code === 200 || json.code === 0) && Array.isArray(json.data)) {
          categories.value = json.data;
        }
      } catch (err) {
        console.error("fetch science categories error", err);
      }
    };

    const handleSearch = () => {
      pagination.page = 1;
      fetchList();
    };

    const resetFilters = () => {
      filters.id = "";
      filters.title = "";
      filters.category_id = "";
      filters.status = "";
      pagination.page = 1;
      fetchList();
    };

    const handlePageChange = (page) => {
      pagination.page = page;
      fetchList();
    };

    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.page = 1;
      fetchList();
    };

    fetchCategories();
    fetchList();

    // 删除功能
    const handleDelete = async (row) => {
      try {
        // 使用 window.confirm 替代 Vue 的 $confirm
        const confirmResult = window.confirm('确定要删除这条记录吗？删除后将无法恢复！');
                console.error('row', row);
        if (confirmResult) {
          // 调用删除API
          const res = await K.science.delete({id: row.id});
          if (res.error) {
            R.msgError(res.msg || '删除失败');
            return;
          }
          
          R.msgSuccess('删除成功');
          fetchList(); // 重新获取列表数据
        }
      } catch (err) {
        console.error('delete error', err);
        R.msgError('删除失败');
      }
    };

    return {
      filters,
      tableData,
      categories,
      loading,
      pagination,
      handleSearch,
      resetFilters,
      handlePageChange,
      handleSizeChange,
      handleAdd,
      handleEdit,
      handleView,
      handleStatusChange,
      handleDelete,
    };
  },
  render() {
    const d = this,
      a = u("el-card"),
      w = u("el-form"),
      p = u("el-form-item"),
      k = u("el-input"),
      b = u("el-select"),
      h = u("el-option"),
      q = u("el-button"),
      N = u("el-table"),
      m = u("el-table-column"),
      $ = u("el-tag"),
      P = u("el-image"),
      L = u("el-pagination"),
      T = ee("loading");
    return (
      i(),
      z("div", Ye, [
        e(
          a,
          { class: "border-none mt-2", shadow: "never" },
          {
            default: l(() => [
              f("div", Je, [
                e(
                  w,
                  { model: d.filters, inline: "", class: "w-100" },
                  {
                    default: l(() => [
                      e(
                        p,
                        { label: "ID", prop: "id" },
                        {
                          default: l(() => [
                            e(
                              k,
                              {
                                modelValue: d.filters.id,
                                "onUpdate:modelValue":
                                  d.$_id || (d.$_id = (t) => (d.filters.id = t)),
                                clearable: "",
                                placeholder: "请输入ID",
                                onKeyup:
                                  d.$_enterId ||
                                  (d.$_enterId = (t) =>
                                    t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "标题", prop: "title" },
                        {
                          default: l(() => [
                            e(
                              k,
                              {
                                modelValue: d.filters.title,
                                "onUpdate:modelValue":
                                  d.$_title ||
                                  (d.$_title = (t) => (d.filters.title = t)),
                                clearable: "",
                                placeholder: "请输入标题关键词",
                                onKeyup:
                                  d.$_enterTitle ||
                                  (d.$_enterTitle = (t) =>
                                    t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "分类", prop: "category_id" },
                        {
                          default: l(() => [
                            e(
                              b,
                              {
                                modelValue: d.filters.category_id,
                                "onUpdate:modelValue":
                                  d.$_category ||
                                  (d.$_category = (t) =>
                                    (d.filters.category_id = t)),
                                placeholder: "全部分类",
                                clearable: "",
                                style: { width: "150px", zIndex: 1000 },
                                popperClass: "custom-select-dropdown"
                              },
                              {
                                default: l(() => [
                                  (i(!0),
                                  z(
                                    J,
                                    null,
                                    X(
                                      d.categories,
                                      (t) => (
                                        i(),
                                        y(
                                          h,
                                          {
                                            key: t.id,
                                            label: t.name,
                                            value: t.id,
                                          },
                                          null,
                                          8,
                                          ["label", "value"],
                                        )
                                      ),
                                    ),
                                    128,
                                  )),
                                ]),
                                _: 1,
                              },
                              8,
                              ["modelValue"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "状态", prop: "status" },
                        {
                          default: l(() => [
                            e(
                              b,
                              {
                                modelValue: d.filters.status,
                                "onUpdate:modelValue":
                                  d.$_status ||
                                  (d.$_status = (t) => (d.filters.status = t)),
                                placeholder: "全部状态",
                                clearable: "",
                                style: { width: "150px", zIndex: 1000 },
                                popperClass: "custom-select-dropdown"
                              },
                              {
                                default: l(() => [
                                  (i(!0),
                                  z(
                                    J,
                                    null,
                                    X(
                                      STATUS_OPTIONS,
                                      (t) => (
                                        i(),
                                        y(
                                          h,
                                          {
                                            key: t.value,
                                            label: t.label,
                                            value: t.value,
                                          },
                                          null,
                                          8,
                                          ["label", "value"],
                                        )
                                      ),
                                    ),
                                    128,
                                  )),
                                ]),
                                _: 1,
                              },
                              8,
                              ["modelValue"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { style: { "margin-right": "0" } },
                        {
                          default: l(() => [
                            e(
                              q,
                              { type: "primary", icon: "Search", onClick: d.handleSearch },
                              {
                                default: l(() => [s("查询")]),
                                _: 1,
                              },
                              8,
                              ["onClick"],
                            ),
                            e(
                        q,
                        { icon: "Refresh", onClick: d.resetFilters, style: { marginLeft: "10px" } },
                        {
                          default: l(() => [s("重置")]),
                          _: 1,
                        },
                        8,
                        ["onClick"],
                      ),
                      e(
                        q,
                        {
                          type: "primary",
                          style: { marginLeft: "10px" },
                           onClick: () => d.handleAdd()
                        },
                        {
                          default: l(() => [s("新增")]),
                          _: 1,
                        },
                        8,
                        ["onClick"],
                      ),
                          ]),
                          _: 1,
                        },
                      ),
                    ]),
                    _: 1,
                  },
                  8,
                  ["model"],
                ),
              ]),
            ]),
            _: 1,
          },
        ),
        e(
          a,
          { class: "border-none mt-3", shadow: "never" },
          {
            default: l(() => [
              g(
                e(
                  N,
                  {
                    data: d.tableData,
                    size: "large",
                    stripe: "",
                    "row-key": "id",
                    "header-cell-style": {
                      background: "var(--el-bg-color-page)",
                    },
                  },
                  {
                    default: l(() => [
                      e(m, { prop: "id", label: "ID", width: "85" }),
                      e(m, { prop: "title", label: "标题", width: "220", "show-overflow-tooltip": "" }),
                      e(
                        m,
                        { label: "封面", width: "120" },
                        {
                          default: l(({ row: t }) => [
                            e(
                              P,
                              {
                                src: t.cover_image,
                                fit: "cover",
                                style: { width: "80px", height: "60px" },
                                previewSrcList: t.cover_image ? [t.cover_image] : [],
                              },
                              null,
                              8,
                              ["src", "previewSrcList"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        m,
                        { label: "分类", width: "140" },
                        {
                          default: l(({ row: t }) => [
                            s(
                              V(
                                (t.category && t.category.name) || t.category_name || "-",
                              ),
                              1,
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        m,
                        { label: "作者", width: "180" },
                        {
                          default: l(({ row: t }) => [
                            s(
                              V(
                                t.user
                                  ? `${t.user.name || "-"} (ID: ${t.user.id})`
                                  : t.user_id
                                  ? `用户ID ${t.user_id}`
                                  : "-",
                              ),
                              1,
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        m,
                        { prop: "views", label: "浏览量", width: "100" },
                      ),
                      e(
                        m,
                        { prop: "likes", label: "点赞数", width: "100" },
                      ),
                      // e(
                      //   m,
                      //   { label: "发布时间", width: "180" },
                      //   {
                      //     default: l(({ row: t }) => [
                      //       s(V(formatTimestamp(t.publish_time)), 1),
                      //     ]),
                      //     _: 1,
                      //   },
                      // ),
                      e(
                        m,
                        { label: "状态", width: "100" },
                        {
                          default: l(({ row: t }) => [
                            e(
                              $,
                              { 
                                type: t.status === 1 ? "success" : 
                                       t.status === 2 ? "info" : 
                                       t.status === 3 ? "warning" : "default",
                                onClick: () => d.handleStatusChange(t)
                              },
                              {
                                default: l(() => [
                                  s(V(formatStatusText(t.status)), 1),
                                ]),
                                _: 2,
                              },
                              1032,
                              ["type", "onClick"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        m,
                        { label: "操作", width: "200", fixed: "right" },
                        {
                          default: l(({ row: t }) => [
                            // e(
                            //   q,
                            //   {
                            //     type: "primary",
                            //     size: "small",
                            //     style: { marginRight: "10px" },
                            //     onClick: () => d.handleView(t)
                            //   },
                            //   {
                            //     default: l(() => [s("查看")]),
                            //     _: 1,
                            //   },
                            //   8,
                            //   ["onClick"],
                            // ),
                            e(
                              q,
                              {
                                type: "success",
                                size: "small",
                                style: { marginRight: "10px" },
                                onClick: () => d.handleEdit(t)
                              },
                              {
                                default: l(() => [s("编辑")]),
                                _: 1,
                              },
                              8,
                              ["onClick"],
                            ),
                            e(
                              q,
                              {
                                type: "danger",
                                size: "small",
                                onClick: () => d.handleDelete(t)
                              },
                              {
                                default: l(() => [s("删除")]),
                                _: 1,
                              },
                              8,
                              ["onClick"],
                            )
                          ]),
                          _: 1,
                        },
                      ),
                      
                      e(
                        m,
                        {prop: "update_time",  label: "更新时间", width: "180" },
                        // {
                        //   default: l(({ row: t }) => [
                        //     s(V(formatTimestamp(t.update_time)), 1),
                        //   ]),
                        //   _: 1,
                        // },
                      ),
                    ]),
                    _: 1,
                  },
                  8,
                  ["data", "header-cell-style"],
                ),
                [[T, d.loading]],
              ),
              f("div", Qe, [
                e(
                  L,
                  {
                    background: "",
                    layout: "total, sizes, prev, pager, next, jumper",
                    total: d.pagination.total,
                    "page-sizes": [10, 20, 50, 100],
                    "current-page": d.pagination.page,
                    "page-size": d.pagination.pageSize,
                    onCurrentChange: d.handlePageChange,
                    onSizeChange: d.handleSizeChange,
                    "hide-on-single-page": false,
                  },
                  null,
                  8,
                  [
                    "total",
                    "current-page",
                    "page-size",
                    "onCurrentChange",
                    "onSizeChange",
                    "hide-on-single-page",
                  ],
                ),
              ]),
            ]),
            _: 1,
          },
        ),
      ])
    );
  },
};

export { et as default };
